<template>
  <div>
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 搜索框输入 -->
    <van-search
      v-model.trim="key"
      show-action
      @input="onInput"
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 历史记录区域 -->

    <van-cell-group v-if="!key">
      <van-cell title="历史记录" />
      <van-cell
        v-for="(item, index) in historyList"
        :key="index"
        :title="item"
        @click="$router.push({ name: 'result', query: { key: item } })"
      />
    </van-cell-group>
    <van-cell-group v-else>
      <van-cell
        v-for="(item, index) in colorSuggests"
        :key="index"
        @click="
          $router.push({ name: 'result', query: { key: suggestList[index] } })
        "
        icon="search"
      >
        <div v-html="item"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { searchAPI, suggestAPI } from "@/api";
export default {
  data() {
    return {
      key: "",
      suggestList: [],
      searchlist: [],
      showSearch: true,
      historyList: JSON.parse(window.localStorage.getItem("history")) || [],
    };
  },
  methods: {
    onSearch() {
      if (this.key) {
        if (this.historyList.indexOf(this.key) == -1) {
          this.historyList.unshift(this.key);
          window.localStorage.setItem(
            "history",
            JSON.stringify(this.historyList)
          );
        }
      }

      this.$router.push({
        name: "result",
        query: {
          key: this.key,
        },
      });
    },
    onInput() {
      // 把要执行的代码放到一个定时器里，如果短时间内频繁触发
      // 就频繁让定时器重新计时
      clearTimeout(this.timerId);

      this.timerId = setTimeout(async () => {
        // 有值发请求
        if (this.key) {
          // 拿到输入的内容，发请求获取联想词汇
          let res = await suggestAPI({
            q: this.key,
          });

          this.suggestList = res.data.data.options;
          console.log(this.suggestList);
        }
      }, 500);
    },
  },
  //   计算属性
  computed: {
    colorSuggests() {
      // 遍历搜索联想的数组，产生一个新数组
      let reg = new RegExp(this.key, "ig");
      return this.suggestList.map((v) =>
        v.replace(reg, `<span style="color:red;">${this.key}</span>`)
      );
    },
  },
};
</script>

<style>
</style>